package com.itbaizhan;
//效率测试
/**使用StringBuilder进行字符串的拼接
 * 注：字符串拼接就用StringBuilder*/
public class TestString04 {
    /**使用String进行字符串的拼接  不可以这样写  内存占用大*/
    public static void main(String[] args) {
        String str1 = "";

        long num1 = Runtime.getRuntime().freeMemory();//获取系统剩余内存空间
        long time1 = System.currentTimeMillis();//获取系统的当前时间
        for(int i=0;i<1000;i++){
            str1 = str1+i;//相当于产生了1000w个对象
        }
        long num2 = Runtime.getRuntime().freeMemory();
        long time2 = System.currentTimeMillis();
        System.out.println("String占用内存："+(num1-num2));
        System.out.println("String占用时间："+(time2-time1));
        /**使用StringBuilder进行字符串的拼接  */
        StringBuilder sb1 = new StringBuilder("");//双引号
        long num3 = Runtime.getRuntime().freeMemory();
        long time3 = System.currentTimeMillis();
        for(int i=0;i<1000;i++){
            sb1.append(i);    //用append 拼接字符串
        }
        long num4 = Runtime.getRuntime().freeMemory();
        long time4 = System.currentTimeMillis();
        System.out.println("StringBuilder占用内存："+(num3-num4));
        System.out.println("StringBuilder占用时间："+(time4-time3));
    }
}
